package cc.dd.marketing.core;

import cc.dd.marketing.api.constant.ResultDTO;
import cc.dd.marketing.api.response.base.BaseResponse;
import cc.dd.marketing.common.ContextParam;
import cc.dd.marketing.common.ResultUtil;
import cc.dd.marketing.core.base.BusinessHandler;
import cc.dd.marketing.system.exception.base.BusinessException;
import cc.dd.marketing.system.exception.response.ResultCodeEnum;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 活动调度器
 *
 * @author dongsufeng
 * @date 2022/9/9 11:30 AM
 */
@Component
@Slf4j
public class BusinessDispatcher {
    @Resource
    private CommonFactory commonFactory;


    public <T extends BaseResponse> ResultDTO<T> dispatcher(ContextParam contextParam) {
        StopWatch watch = StopWatch.createStarted();
        T response;
        String beanName = contextParam.getRequest().getClass().getName();
        log.info("执行{}开始requestContext:{}", beanName, JSON.toJSONString(contextParam));
        try {
            BusinessHandler businessHandler = commonFactory.getBusinessHandler(contextParam.getFunctionCode(), contextParam.getBusinessNo());
            response = businessHandler.handle(contextParam);
        } catch (BusinessException e) {
            if (ResultCodeEnum.REQUEST_SUCCESS.getCode().equals(e.getCode())){
                return ResultUtil.success(null);
            }
            log.error("执行业务error businessNo:{}", contextParam.getBusinessNo(), e);
            return ResultUtil.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("执行error系统Exception businessNo:{}", contextParam.getBusinessNo(), e);
            return ResultUtil.fail(ResultCodeEnum.SYSTEM_ERROR.getCode(), "系统Exception异常");
        } catch (Throwable e) {
            log.error("执行error系统Throwable businessNo:{}", contextParam.getBusinessNo(), e);
            return ResultUtil.fail(ResultCodeEnum.SYSTEM_ERROR.getCode(), "系统Throwable异常");
        }
        log.info("执行结束 businessNo:{} response:{} time:{}", contextParam.getBusinessNo(), JSON.toJSONString(response), watch.getTime());
        return ResultUtil.success(response);
    }
}
